function getIp() {
    if (!window.platform) {
        return `${window.location.origin}/`;
    } else {
        return `http://${window.platform.ip}:${window.platform.port}/`;
    }
}
layui.use(['element','table','form','layer','util','laydate','upload'], function(){
    var table = layui.table,
        form = layui.form,
        $ = layui.jquery,
        layer = layui.layer,
        upload = layui.upload,
    laydate = layui.laydate;

    laydate.render({
        elem: '#startTime'
        ,type: 'time'
        ,trigger:'click'//解决一闪而过的问题
        ,done:function(value,data){
            let endTime = $("#endTime").val();
            if(!endTime){return; }
            if(compareTime(value,endTime)){
                saveOrUpdateRange(value,endTime);
            }else {
                return layer.msg("开始时间需要小于结束时间",{icon:5});
            }
        }
    });

    function saveOrUpdateRange(startTime,endTime){
        var param = {"type":"待机能耗分析设置","startTime":startTime,"endTime":endTime,"id":$("#homeRangeId").val()}
        $.ajax({
            type: 'post',
            url: '/cddjnhjcxtsysset/cddjnhjcxtsyssetHomeRange/saveOrUpdate',
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(param),
            success: function (res) {
                layer.msg(res.msg);
                $("#homeRangeId").val(res.data);
            },
        });
    }

    laydate.render({
        elem: '#endTime'
        ,type: 'time'
        ,trigger:'click'
        ,done:function(value,data){
            let startTime = $("#startTime").val();
            if(!startTime){return; }
            if(compareTime(startTime,value)){
                saveOrUpdateRange(startTime,value);
            }else {
                return layer.msg("开始时间需要小于结束时间",{icon:5});
            }
        }
    });

    for (let i = 1; i <= 9; i++) {
        laydate.render({
            elem: '#lrny'+i
            ,type: 'month'
        });
    }

    function getJqObjByText(pId,eleLabel,content){
        var ele;
        $("#"+pId+" "+eleLabel+":contains('"+content+"')").each(function(){
        //if($(this).text()==content){ //注：此处不能这样判断，
            if(this.innerHTML==content){
                ele = this; //此处，如果希望直接返回jquery对象，那就给 $(this) 的值
                return false; //加上这句，在找到第一个符合的元素时跳出$.each。
            }
        });
        return ele;
    }
    // 能耗初始化
    $.get('/cddjnhjcxtsysset/cddjnhjcxtsyssetHomeEnergy/list',{},function (res) {
        if(res && res.data){
            res.data.forEach(item=>{
                var trEle = $(getJqObjByText("energyDiv","td",item.type+":")).parent();
                let ysz = item.ysz == null || item.ysz == '' ? 0 : item.ysz;
                let dez = item.dez == null || item.dez == '' ? 0 : item.dez;
                let ydz = item.ydz == null || item.ydz == '' ? 0 : item.ydz;
                trEle.find('td:eq(1)').find('input').val(ysz);
                trEle.find('td:eq(2)').find('input').val(dez);
                trEle.find('td:eq(3)').find('input').val(ydz);
                trEle.find('td:eq(5)').find('input').val(item.dedw);
            });
        }
    });

    // 单价初始化
    $.get('/cddjnhjcxtsysset/cddjnhjcxtsyssetHomePrice/list',{},function (res) {
        if(res && res.data){
            res.data.forEach(item=>{
                let dj = item.numValue == null || item.numValue == '' ? 0 : item.numValue;
                $(getJqObjByText("priceDiv","td",item.type+":")).next('td').find('input').val(dj);
            });
        }
    });

    // 支出初始化

    $("#expendSetting").attr("href",getIp() + "web/cddycockpit/html/show.html?id=CDE2E3AEC1567626E0537C0AA8C0FB18");

    // $.get('/cddjnhjcxtsysset/cddjnhjcxtsyssetHomeExpend/list',{},function (res) {
    //     if(res && res.data){
    //         res.data.forEach(item=>{
    //             var td1Ele = $(getJqObjByText("expendDiv","td",item.type+":"));
    //             td1Ele.next('td').find('input').val(item.amount);
    //             td1Ele.next().next('td').find('input').val(item.yearMonth);
    //         });
    //     }
    // });

    // 所有关联初始化
    initHomeReleava();

    // 工作区间初始化
    $.get('/cddjnhjcxtsysset/cddjnhjcxtsyssetHomeRange/get',{},function (res) {
        if(res && res.data){
            $("#homeRangeId").val(res.data.id);
            $("#startTime").val(res.data.startTime);
            $("#endTime").val(res.data.endTime);
        }
    });

    function initHomeReleava() {
        $.get('/cddjnhjcxtsysset/cddjnhjcxtsyssetHomeReleva/list',{},function (res) {
            if(res && res.data){
                res.data.forEach(item=>{
                    var typeText = item.type;
                    if(typeText){
                        let sbnxLabel = getJqObjByText("sbnxForm","label",typeText+":");
                        let zhnhjcszLabel = getJqObjByText("zhnhjcszForm","label",typeText+":");
                        let zdynsbLabel = getJqObjByText("zdynsbForm","label",typeText.substr(2)+":");
                        let jyznhLabel = getJqObjByText("jyznhForm","label",typeText.substr(3)+":");
                        let znhfxszLabel = getJqObjByText("znhfxszForm","label",typeText.substr(5)+":");
                        let djnhfxszLabel = getJqObjByText("djnhfxszForm","label",typeText.substr(6)+":");
                        if(sbnxLabel != undefined){
                            var btnEle = $(sbnxLabel).next('div').find(".relevaBtn");
                            btnEle.attr("id",item.id);
                            if(item.whether == 1){ //关联的
                                btnEle.html("已关联");
                                btnEle.addClass("layui-btn-primary layui-border-green");
                            }else {
                                btnEle.html("未关联");
                                btnEle.removeClass("layui-btn-primary layui-border-green");
                            }
                        }else if(zhnhjcszLabel != undefined){
                            var btnEle4 = $(zhnhjcszLabel).next('div').find(".relevaBtn");
                            btnEle4.attr("id",item.id);
                            if(item.whether == 1){ //关联的
                                btnEle4.html("已关联");
                                btnEle4.addClass("layui-btn-primary layui-border-green");
                            }else {
                                btnEle4.html("未关联");
                                btnEle4.removeClass("layui-btn-primary layui-border-green");
                            }
                            // 去掉 重点
                        }else if(zdynsbLabel != undefined){
                            var btnEle2 = $(zdynsbLabel).next('div').find(".relevaBtn");
                            btnEle2.attr("id",item.id);
                            if(item.whether == 1){ //关联的
                                btnEle2.html("已关联");
                                btnEle2.addClass("layui-btn-primary layui-border-green");
                            }else {
                                btnEle2.html("未关联");
                                btnEle2.removeClass("layui-btn-primary layui-border-green");
                            }
                            // 去掉 近一周
                        }else if(jyznhLabel != undefined){
                            var btnEle3 = $(jyznhLabel).next('button');
                            btnEle3.attr("id",item.id);
                            if(item.whether == 1){ //关联的
                                btnEle3.html("已关联");
                                btnEle3.addClass("layui-btn-primary layui-border-green");
                            }else {
                                btnEle3.html("未关联");
                                btnEle3.removeClass("layui-btn-primary layui-border-green");
                            }
                        }else if(znhfxszLabel != undefined){ // 去掉 总能耗分析
                            var btnEle5 = $(znhfxszLabel).next('div').find(".relevaBtn");
                            btnEle5.attr("id",item.id);
                            if(item.whether == 1){ //关联的
                                btnEle5.html("已关联");
                                btnEle5.addClass("layui-btn-primary layui-border-green");
                            }else {
                                btnEle5.html("未关联");
                                btnEle5.removeClass("layui-btn-primary layui-border-green");
                            }
                        }else if(djnhfxszLabel != undefined){ // 去掉 待机能耗分析
                            var btnEle6 = $(djnhfxszLabel).next('div').find(".relevaBtn");
                            btnEle6.attr("id",item.id);
                            if(item.whether == 1){ //关联的
                                btnEle6.html("已关联");
                                btnEle6.addClass("layui-btn-primary layui-border-green");
                            }else {
                                btnEle6.html("未关联");
                                btnEle6.removeClass("layui-btn-primary layui-border-green");
                            }
                        }
                    }
                });
            }
        });
    }

    // 附件信息初始化
    $.get('/cddjnhjcxtsysset/cddjnhjcxtsyssetHomeAttach/list',{},function (res) {
        if(res && res.data){
            res.data.forEach(item=>{
                var aEle = $(getJqObjByText("attachForm","label",item.name+":")).next('a');
                var btnEle = aEle.next("button");
                if(item.path && item.fileName){
                    aEle.attr("href",'/upload/'+item.path);
                    aEle.html(item.fileName);
                    $(btnEle).html("重新上传");
                }
            });
        }
    });

    // 能耗保存
    form.on('submit(saveEnergy)',function(data){
        var energyArray = [];
        $('.energyType').each(function (){
            var type = $(this).text().replace(':','');
            var ysz =$(this).parent().find('td:eq(1)').find('input').val();
            var dez =$(this).parent().find('td:eq(2)').find('input').val();
            var ydz =$(this).parent().find('td:eq(3)').find('input').val();
            var dedw =$(this).parent().find('td:eq(5)').find('input').val();
            var item = {type:type,ysz:ysz,dez:dez,ydz:ydz,dedw:dedw};
            energyArray.push(item);
        });
        layer.load();
        $.ajax({
            type: 'post',
            url: '/cddjnhjcxtsysset/cddjnhjcxtsyssetHomeEnergy/saveOrUpdate',
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(energyArray),
            success: function (res) {
                layer.msg(res.msg);
                setTimeout(function () {
                    layer.closeAll();
                },1000);
            },
        });
        return false;
    });

    // 单价保存
    form.on('submit(savePrice)',function(data){
        var priceArray = [];
        $('.priceType').each(function (){
            var type = $(this).text().replace(':','');
            var numValue =$(this).next('td').find('input').val();
            var item = {type:type,numValue:numValue};
            priceArray.push(item);
        });
        layer.load();
        $.ajax({
            type: 'post',
            url: '/cddjnhjcxtsysset/cddjnhjcxtsyssetHomePrice/saveOrUpdate',
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(priceArray),
            success: function (res) {
                layer.msg(res.msg);
                setTimeout(function () {
                    layer.closeAll();
                },1000);
            },
        });
        return false;
    });

    // 支出保存
    form.on('submit(saveExpend)',function(data){
        var expendArray = [];
        $('.expendType').each(function (){
            var type = $(this).text().replace(':','');
            var amount =$(this).next('td').find('input').val();
            var yearMonth =$(this).next().next('td').find('input').val();
            var item = {type:type,amount:amount,yearMonth:yearMonth};
            expendArray.push(item);
        });
        layer.load();
        $.ajax({
            type: 'post',
            url: '/cddjnhjcxtsysset/cddjnhjcxtsyssetHomeExpend/saveOrUpdate',
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(expendArray),
            success: function (res) {
                layer.msg(res.msg);
                setTimeout(function () {
                    layer.closeAll();
                },1000);
            },
        });
        return false;
    });

    let relevaSetDiv1,relevaSetDiv2,relevaSetDiv3,relevaSetDiv4;
    // 设备能效及环境监测设置
    $(".relevaSetBtn").on('click',function (){
        let relevaId = $(this).prev().attr("id");
        var labelName = $(this).parent().prev().text().replace(':','');
        $("#relevaType").val(labelName);
        if(labelName.lastIndexOf("用电量") != -1){
            renderTable(relevaId,"DBGL");
        }else if(labelName.lastIndexOf("制冷量") != -1){
            renderTable(relevaId,"LJLBGL");
        }else if(labelName.lastIndexOf("制热量") != -1){
            renderTable(relevaId,"RJLBGL");
        }else {
            renderTable(relevaId,"QTBGGL","仪表设备");
        }
        relevaSetDiv1 = layer.open({
            type: 1
            , title: labelName + '设备选择'
            , area: ['55%', '90%']
            , content: $('#deviceChooseDiv')
        });
    });
    // 重点用能设备及部门设置
    $(".relevaSetBtn2").on('click',function (){
        let relevaId = $(this).prev().attr("id");
        var labelName = $(this).parent().prev().text().replace(':','');
        $("#relevaType").val("重点"+labelName);
        if(labelName.lastIndexOf("用电") != -1){
            renderTable(relevaId,"DBGL");
        }else if(labelName.lastIndexOf("用水") != -1){
            renderTable(relevaId,"SBGL");
        }else if(labelName.lastIndexOf("用天然气") != -1){
            renderTable(relevaId,"QTBGGL",'仪表设备','天然气');
        }else if(labelName.lastIndexOf("用汽油") != -1){
            renderTable(relevaId,"QTBGGL",'仪表设备','汽油');
        }else {
            renderTable(relevaId,"QTBGGL","",'其他');
        }
        relevaSetDiv2 = layer.open({
            type: 1
            , title: labelName + '设备选择'
            , area: ['55%', '90%']
            , content: $('#deviceChooseDiv')
        });
    });
    // 综合能耗检测设置
    $(".zhnhSetBtn").on('click',function (){
        let relevaId = $(this).prev().attr("id");
        var labelName = $(this).parent().prev().text().replace(':','');
        $("#relevaType").val(labelName);
        if(labelName.lastIndexOf("用电") != -1 || labelName.lastIndexOf("电量") != -1){
            renderTable(relevaId,"DBGL");
        }else if(labelName.lastIndexOf("市政热力") != -1){
            renderTable(relevaId,"RJLBGL");
        }else if(labelName.lastIndexOf("天然气") != -1){
            renderTable(relevaId,"QTBGGL",'仪表设备','天然气');
        }else {
            renderTable(relevaId,"QTBGGL","",'其他');
        }
        relevaSetDiv1 = layer.open({
            type: 1
            , title: labelName + '设备选择'
            , area: ['55%', '90%']
            , content: $('#deviceChooseDiv')
        });
    });

    // 总能耗分析设置
    $(".znhfxszBtn").on('click',function (){
        let relevaId = $(this).prev().attr("id");
        var labelName = $(this).parent().prev().text().replace(':','');
        $("#relevaType").val("总能耗分析"+labelName);
        if(labelName.lastIndexOf("用电") != -1){
            renderTable(relevaId,"DBGL");
        }else if(labelName.lastIndexOf("用水") != -1){
            renderTable(relevaId,"SBGL");
        }else if(labelName.lastIndexOf("用天然气") != -1){
            renderTable(relevaId,"QTBGGL",'仪表设备','天然气');
        }else if(labelName.lastIndexOf("用汽油") != -1){
            renderTable(relevaId,"QTBGGL",'仪表设备','汽油');
        }else if(labelName.lastIndexOf("用柴油") != -1){
            renderTable(relevaId,"QTBGGL",'仪表设备','柴油');
        }else if(labelName.lastIndexOf("用液化气") != -1){
            renderTable(relevaId,"QTBGGL",'仪表设备','液化气');
        }else if(labelName.lastIndexOf("用热") != -1){
            renderTable(relevaId,"RJLBGL",'仪表设备');
        }else if(labelName.lastIndexOf("用冷") != -1){
            renderTable(relevaId,"LJLBGL",'仪表设备');
        }else {
            renderTable(relevaId,"QTBGGL",'','其他');
        }
        relevaSetDiv1 = layer.open({
            type: 1
            , title: labelName + '设备选择'
            , area: ['55%', '90%']
            , content: $('#deviceChooseDiv')
        });
    });

    // 近一周能耗分析图设置
    $(".relevaSetBtn3").on('click',function (){
        let relevaId = $(this).prev().attr("id");
        var labelName = $(this).prev().prev().text().replace(':','');
        $("#relevaType").val("近一周"+labelName);
        if(labelName.lastIndexOf("用电") != -1){
            renderTable(relevaId,"DBGL");
        }else if(labelName.lastIndexOf("用水") != -1){
            renderTable(relevaId,"SBGL");
        }else {
            renderTable(relevaId,"QTBGGL");
        }
        relevaSetDiv3 = layer.open({
            type: 1
            , title: labelName + '设备选择'
            , area: ['55%', '90%']
            , content: $('#deviceChooseDiv')
        });
    });

    // 待机能耗分析设置
    $(".djnhfxszBtn").on('click',function (){
        let relevaId = $(this).prev().attr("id");
        var labelName = $(this).parent().prev().text().replace(':','');
        $("#relevaType").val("待机能耗分析"+labelName);
        if(labelName.lastIndexOf("用电") != -1){
            renderTable(relevaId,"DBGL");
        }else if(labelName.lastIndexOf("用水") != -1){
            renderTable(relevaId,"SBGL");
        }else if(labelName.lastIndexOf("用天然气") != -1){
            renderTable(relevaId,"QTBGGL",'仪表设备','天然气');
        }else if(labelName.lastIndexOf("用汽油") != -1){
            renderTable(relevaId,"QTBGGL",'仪表设备','汽油');
        }else {
            renderTable(relevaId,"QTBGGL",'','其他');
        }
        relevaSetDiv4 = layer.open({
            type: 1
            , title: labelName + '设备选择'
            , area: ['55%', '90%']
            , content: $('#deviceChooseDiv')
        });
    });

    $("#cancel_form").on('click',function () {
        if(relevaSetDiv1){layer.close(relevaSetDiv1);}
        if(relevaSetDiv2){layer.close(relevaSetDiv2);}
        if(relevaSetDiv3){layer.close(relevaSetDiv3);}
        if(relevaSetDiv4){layer.close(relevaSetDiv4);}
    });

    form.on('submit(choosedevice_form)',function(obj){
        var checkStatus = table.checkStatus('deviceTable');
        var	data = checkStatus.data;
        let len = data.length;
        if(len === 0){
            layer.tips("请至少选择一条记录!",this);
            return false;
        }
        let type = $("#relevaType").val();
        if(type == '室内环境传感器' || type == "室外环境传感器"){
            if(len != 1){
                layer.tips(type+"只能选择一个设备!",this);
                return false;
            }
        }
        var paramArr = [];
        let relevaId = $("#relevaId").val();
        data.forEach(item=>{
            let obj = {relevaId:relevaId,deviceName:item.field02,deviceMac:item.field14,type:type,deviceId:item.id};
            paramArr.push(obj);
        });
        let loaddiv = layer.load();
        $.ajax({
            type: 'post',
            url: '/cddjnhjcxtsysset/cddjnhjcxtsyssetHomeDevice/saveOrUpdate',
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(paramArr),
            success: function (res) {
                let newrelevaId = res.data;
                $("#relevaId").val(newrelevaId);
                layer.msg(res.msg,{
                    time:500,
                    end:function () {
                        initHomeReleava();
                        table.reload('choosedDeviceTable',{
                            where: {relevaId:newrelevaId}
                            ,page:  {
                                curr:1
                            }
                        });
                        layer.close(loaddiv);
                    }
                });
            }
        });
        return false;
    });

    table.on('tool(choosedDeviceTable)',function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'delete':
                layer.confirm('确定要删除吗?', {
                }, function(){
                    let index = layer.load();
                    $.get('/cddjnhjcxtsysset/cddjnhjcxtsyssetHomeDevice/delete',{id:data.id,type:$("#relevaType").val()},function (res) {
                        layer.msg(res.msg,{
                            time:500,
                            end:function () {
                                initHomeReleava();
                                table.reload('choosedDeviceTable',{
                                    where: {relevaId:$("#relevaId").val(),}
                                    ,page:  {
                                        curr:1
                                    }
                                });
                                layer.close(index);
                            }
                        });
                    });
                });
                break;
        }
    });

    function queryDevice(){
        var nameOrCode = $("#nameOrCode").val();
        table.reload('deviceTable',{
            where: {nameOrCode:nameOrCode,}
            ,page:  {
                curr:1
            }
        });
    }

    form.on('submit(queryDevice)',function () {
        queryDevice();
        return false;
    });

    function renderTable(relevaId,type,deviceType,otherType) {
        if(relevaId){
            $("#relevaId").val(relevaId);
        }else {
            $("#relevaId").val('');
        }
        table.render({
            elem: '#choosedDeviceTable'
            ,url:'/cddjnhjcxtsysset/cddjnhjcxtsyssetHomeDevice/listChoosed'
            ,title: '已选择的设备列表'
            ,where: {'relevaId': relevaId}
            ,cols: [[
                {field: 'xh',type:'numbers', title: '序号',}
                ,{field:'deviceName', title:'设备名称',align:'center'}
                ,{field:'deviceMac', title:'设备mac',align:'center'}
                ,{field:'right',title:'操作',toolbar:'#barOperate',align:'center'}
            ]]
        });
        table.render({
            elem: '#deviceTable'
            ,url:'/cddjnhjcxtsysset/cddjnhjcxtsyssetHomeDevice/list'
            ,title: '设备列表'
            // 设备类型：电表DBGL 水表SBGL 热计量RJLBGL 冷计量表LJLBGL 其他QTBGGL
            ,where: {"type": type,"nameOrCode":"","deviceType":deviceType,"otherType":otherType}
            ,cols: [[
                {field: 'xh',type:'numbers', title: '序号',}
                ,{type:'checkbox'}
                ,{field:'field02', title:'设备名称',align:'center'}
                ,{field:'field03', title:'设备编号',align:'center'}
                //,{field:'field14', title:'设备mac',align:'center'}
                ,{field:'field11', title:'设备类型',align:'center'}
                ,{field:'position', title:'安装位置',align:'center'}
            ]]
        });
    }

    // $(".relevaBtn").on('click',function (){
    //     var type = $(this).prev().text().replace(':','');
    //     var isNotRelevaed = $(this).hasClass("layui-btn-primary");
    //     var whether = isNotRelevaed ? 2 : 1;
    //     var record = {type:type,whether:whether};
    //     $.ajax({
    //         type: 'post',
    //         url: '/cddjnhjcxtsysset/cddjnhjcxtsyssetHomeReleva/saveOrUpdate',
    //         contentType: "application/json;charset=utf-8",
    //         dataType: 'json',
    //         data: JSON.stringify(record),
    //         success: function (res) {
    //             layer.msg(res.msg);
    //             setTimeout(function () {
    //                 layer.closeAll();
    //             },1000);
    //         },
    //     });
    //     if(isNotRelevaed){
    //         $(this).html("未关联");
    //     }else {
    //         $(this).html("已关联");
    //     }
    //     $(this).toggleClass("layui-btn-primary layui-border-green");
    // });

    renderUpload('sytpUpload','首页图片');
    renderUpload('dwjjUpload','单位简介');
    renderUpload('ggjgUpload','公共机构基本信息表');
    renderUpload('ggjgbjUpload','公共机构本级基本情况汇总表');

    function renderUpload(eleId,name){
        upload.render({
            elem: '#'+eleId
            ,url: '/cddjnhjcxtsysset/cddjnhjcxtsyssetHomeAttach/uploadFiles'
            ,before: function(obj){
                obj.preview(function(index, file, result){
                    $("#"+eleId).prev("a").html(file.name);
                    //$('#demo1').attr('src', result); //图片链接（base64）
                });
                layer.msg('上传中', {icon: 16, time: 0});
            }
            ,accept: 'images'
            ,data: {name: name}
            ,done: function(res){
                if(res.status != 200){
                    return layer.msg('上传失败,请联系管理员');
                }
                $("#"+eleId).prev("a").attr("href",res.data);
                layer.closeAll();
                layer.msg(res.msg,{icon:1});
            }
            ,error: function(){
            }
        });
    }

});

function compareTime(time1,time2) {
    return time_to_sec(time2) - time_to_sec(time1) > 0;
}

//将时分秒转为时间戳
function time_to_sec(time) {
    if (time !== null) {
        var hour = time.split(":")[0];
        var min = time.split(":")[1];
        var sec = time.split(":")[2];
        return  Number(hour * 3600) + Number(min * 60) + Number(sec);
    }
}